<template>
  <div class="app-pro-basicLayout-content-wrap">
    <div class="app-pro-pages-content">
      <div class="app-pro-table-search">
        <el-form :inline="true" :model="formInline" ref="formInline" label-width="80px" size="small" class="form-flex-item">
          <el-row :gutter="20">
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <el-form-item :label="'검색'|language" prop="keyword">
                <el-input v-model="formInline.keyword" :placeholder="'검색어: 제목, 기업명, 출처'|language" @keyup.enter.native="handleSearch"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="6" :sm="6" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">{{'검색'|language}}</el-button>
                <el-button size="small" @click="resetForm('formInline')">{{'초기화'|language}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-pro-pages-table">
        <div class="main-card">
          <div class="main-table-toolbar">
            <div class="main-table-toolbar-title">
              <div class="main-table-toolbar-title-only">채용정보 관리</div>
            </div>
            <div class="main-table-toolbar-option">
              <!-- <el-button type="primary" size="mini" icon="el-icon-plus" style="margin-right:5px" @click="confirmAddJob">{{'추가'|language}}</el-button> -->
              <!--
              <el-divider direction="vertical"></el-divider> -->
              <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'다운로드'|language" placement="top">
                  <i @click="downloadFile('/api/industry/post', '채용정보 관리')" class="el-icon-download"></i>
                </el-tooltip>
              </el-link>
              <!-- <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'초기화'|language" placement="top">
                  <i @click="getJobList()" class="el-icon-refresh-right"></i>
                </el-tooltip>
              </el-link> -->
            </div>
          </div>
          <div class="main-table-wrapper" style="padding: 0">
            <my-table
              :columns="columns"
              :data="data"
              :loading="loading"
              :pagination="pagination"
              :showIndex="true"
              :showSelection="true"
              :cellStyle="{padding: '6px 0'}"
              :headerCellStyle="{background:'rgba(247, 133, 2, 1)',color:'#fff'}"
              @emitSelection="emitSelection"
              @currentChange="currentChange"
              @sortChange="sortChange">
              <template v-slot:status="slotProps">
                <el-tag v-if="slotProps.callback.row.status===0" type="primary" effect="dark" size="small">{{'채용대기'|language}}</el-tag>
                <el-tag v-else-if="slotProps.callback.row.status===1" type="success" effect="dark" size="small">{{'채용중'|language}}</el-tag>
                <el-tag v-else type="info" effect="dark" size="small">{{'채용완료'|language}}</el-tag>
              </template>
              <template v-slot:edit_status="slotProps">
                <el-tag v-if="slotProps.callback.row.edit_status === 0" type="info" effect="dark" size="small">{{'임시저장'|language}}</el-tag>
                <el-tag v-else effect="dark" size="small">{{'작성완료'|language}}</el-tag>
              </template>
              <template v-slot:active="slotProps">
                <el-tag v-if="slotProps.callback.row.active === 0" effect="dark" size="small">{{'노출됨'|language}}</el-tag>
                <el-tag v-else type="info" effect="dark" size="small">{{'미노출'|language}}</el-tag>
              </template>
              <template v-slot:is_important="slotProps">
                <el-tag v-if="slotProps.callback.row.is_important === 1" type="info" effect="dark" size="small">{{'주요채용공고'|language}}</el-tag>
                <el-tag v-else effect="dark" size="small">{{'일반채용공고'|language}}</el-tag>
              </template>
              <template v-slot:companyName="slotProps">
                <el-link v-if="slotProps.callback.row.companyUrl" :href="slotProps.callback.row.companyUrl" target="_blank">{{slotProps.callback.row.companyName}}</el-link>
              </template>
              <template v-slot:operation="slotProps">
                <el-button
                  @click.native.prevent="handleEdit(slotProps.callback.row)"
                  type="text">
                  {{'수정'|language}}
                </el-button>
                <!-- <el-divider direction="vertical"></el-divider> -->
                <el-popconfirm
                  title="삭제하시겠습니까"
                  @onConfirm="handleDeleteJob(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    style="padding-left:15px;color:#f56c6c">
                    {{'삭제'|language}}
                  </el-button>
                </el-popconfirm>
              </template>
            </my-table>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="dialogForm.title"
      custom-class="dialog-content"
      :visible.sync="dialogForm.dialogVisible"
      :destroy-on-close="false"
      top="5%"
      width="1100px">
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formInfo.ref"
          :data="formInfo.data"
          :field-list="formInfo.fieldList"
          :rules="formInfo.rules"
          :label-width="formInfo.labelWidth"
          :list-type-info="listTypeInfo">
          <template v-slot:form-item-has_many_job >
            <div>
              <div v-for="(item,index) in formInfo.data.has_many_job" :key="index" style="margin-bottom:10px">
                <el-cascader v-model="item.job_id" :options="hasManyJobOption" style="width:500px;" clearable filterable></el-cascader>
                <el-button @click="formInfo.data.has_many_job.splice(index,1)" style="margin-left:10px">삭제</el-button>
              </div>
              <el-button icon="el-icon-plus" @click="if(formInfo.data.has_many_job.length<5) formInfo.data.has_many_job.push({job_id:[]})">추가</el-button>
            </div>
          </template>
          <template v-slot:form-item-has_many_area >
            <div>
              <div v-for="(item,index) in formInfo.data.has_many_area" :key="index" style="margin-bottom:10px">
                <el-cascader v-model="item.area_id" :options="hasManyAreaOption" style="width:500px;" clearable filterable></el-cascader>
                <el-button @click="formInfo.data.has_many_area.splice(index,1)" style="margin-left:10px">삭제</el-button>
              </div>
              <el-button icon="el-icon-plus" @click="if(formInfo.data.has_many_area.length<3) formInfo.data.has_many_area.push({area_id:[]})">추가</el-button>
            </div>
          </template>
          <template v-slot:form-item-employee >
            <div>
              <div v-for="(item,index) in formInfo.data.employee" :key="index" style="margin-bottom:10px">
                <el-select v-model="item.id">
                  <el-option
                    v-for="e in employeeOption"
                    :key="e.value"
                    :label="e.label"
                    :value="e.value">
                  </el-option>
                </el-select>
                <el-button @click="formInfo.data.employee.splice(index,1)" style="margin-left:10px">삭제</el-button>
              </div>
              <el-button icon="el-icon-plus" @click="if(formInfo.data.employee.length<3) formInfo.data.employee.push({id:['']})">추가</el-button>
            </div>
          </template>
          <template v-slot:form-item-iframe >
            <Summernote :noteContent="noteContent"></Summernote>
          </template>
        </form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogForm.dialogVisible = false">{{'취소'|language}}</el-button>
        <el-button size="small" type="primary" @click="handleSubmitJob">{{'확인'|language}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDictData, getIndustry, getJobIndex, getAreaIndex } from '@/api/app'
import { publicEvents } from '@/mixins'
import { mergeObjOfValue, deepClone, changeOption, getFathersById } from '@/utils'
import FormPage from '_c/FormPage'
import myTable from '_c/Table'
import * as jobApi from '@/api/job/index'
import Summernote from '_c/Summernote'
const formInfoData = {
  id: '',
  title: '',
  deadline: '',
  is_important: '',
  readCount: 0,
  applyCount: 0,
  career: '',
  careerMin: '',
  careerMax: '',
  endEducation: '',
  salaryMin: '',
  salaryMax: '',
  industry1: [],
  employee: [],
  employee1: '',
  employee2: '',
  employee3: '',
  salaryFix: '',
  has_many_job: [],
  has_many_area: [],
  status: 0,
  job_number: 0,
  edit_status: 0,
  salaryUnit: ''
}
export default {
  name: 'job-info',
  data () {
    return {
      formInline: {
        keyword: ''
      },
      columns: [{
        label: '채용상태',
        prop: '',
        width: 100,
        slot: 'status',
        sortable: true
      }, {
        label: '노출여부',
        prop: '',
        width: 100,
        slot: 'active',
        sortable: true
      }, {
        label: '수정상태',
        prop: 'edit_status',
        width: 100,
        slot: 'edit_status',
        sortable: true
      }, {
        label: '채용공고 유형',
        prop: 'is_important',
        width: 140,
        slot: 'is_important',
        sortable: true
      }, {
        label: '제목',
        prop: 'title',
        sortable: true
      }, {
        label: '기업명',
        prop: '',
        slot: 'companyName',
        sortable: true
      }, {
        label: '마감시간',
        prop: 'deadline',
        sortable: true
      }, {
        label: '출처',
        prop: 'source',
        sortable: true
      }, {
        label: '인원수',
        prop: 'job_number',
        sortable: true
      }, {
        label: '지원수',
        prop: 'applyCount',
        sortable: true
      }, {
        label: '관리',
        prop: '',
        width: 160,
        align: 'left',
        slot: 'operation'
      }],
      data: [],
      pagination: {
        currentPage: 1,
        pageSize: 15
      },
      selectionData: [],
      loading: true,
      dialogForm: {
        dialogVisible: false,
        title: '추가'
      },
      listTypeInfo: {
        status: [
          {
            label: '채용대기',
            value: 0
          },
          {
            label: '채용중',
            value: 1
          },
          {
            label: '채용완료',
            value: 2
          }
        ],
        edit_status: [
          {
            label: '작성중',
            value: 0
          },
          {
            label: '수정완료',
            value: 1
          }
        ],
        is_important: [
          {
            label: '일반채용공고',
            value: 0
          },
          {
            label: '주요채용공고',
            value: 1
          }
        ],
        industry1: [],
        salaryFix: [
          {
            label: '회사내규에 따름',
            value: 0
          },
          {
            label: '면접후 결정',
            value: 1
          }
        ],
        career: [],
        endEducation: [],
        salaryUnit: []
      },
      formInfo: {
        ref: null,
        data: formInfoData,
        fieldList: [
          { label: '채용공고 유형', value: 'is_important', type: 'select', list: 'is_important', className: 'el-form-block', required: true },
          { label: '수정상태', value: 'edit_status', type: 'select', list: 'edit_status', className: 'el-form-block', required: true },
          { label: '채용상태', value: 'status', type: 'select', className: 'el-form-block', required: true, list: 'status' },
          { label: '제목', value: 'title', type: 'input', className: 'el-form-block', required: true },
          { label: '마감시간', value: 'deadline', type: 'date', className: 'el-form-block', required: true },
          { label: '조회수', value: 'readCount', type: 'inputNumber', className: 'el-form-block', required: true },
          { label: '지원수', value: 'applyCount', type: 'inputNumber', className: 'el-form-block', required: true },
          { label: '채용경력', value: 'career', type: 'select', list: 'career', className: 'el-form-block', required: true },
          { label: '최소경력', value: 'careerMin', type: 'input', className: 'el-form-block', required: true },
          { label: '최고경력', value: 'careerMax', type: 'input', className: 'el-form-block', required: true },
          { label: '최종학력', value: 'endEducation', type: 'select', list: 'endEducation', className: 'el-form-block', required: true },
          { label: '급여 결정방식', value: 'salaryFix', type: 'select', list: 'salaryFix', className: 'el-form-block', required: true },
          { label: '급여 형태', value: 'salaryUnit', type: 'select', list: 'salaryUnit', className: 'el-form-block', required: true },
          { label: '최저급여', value: 'salaryMin', type: 'input', className: 'el-form-block', required: true },
          { label: '최고급여', value: 'salaryMax', type: 'input', className: 'el-form-block', required: true },
          // { label: '고용형태', value: 'employee1', type: 'select', className: 'el-form-block', required: true, list: 'employee1' },
          // { label: '고용형태', value: 'employee2', type: 'select', className: 'el-form-block', required: true, list: 'employee1' },
          // { label: '고용형태', value: 'employee3', type: 'select', className: 'el-form-block', required: true, list: 'employee1' },
          { label: '고용형태', value: 'employee', slot: true, className: 'el-form-block', required: true },
          { label: '산업', value: 'industry1', width: '260', type: 'cascader', className: 'el-form-block', clearable: true, filterable: true, required: true, list: 'industry1' },
          { label: '모집인원수', value: 'job_number', type: 'inputNumber', className: 'el-form-block', required: true },
          { label: '채용직종', value: 'has_many_job', slot: true, className: 'el-form-block', required: true }, // 5
          { label: '근무지역', value: 'has_many_area', slot: true, className: 'el-form-block', required: true }, // 3
          { label: '상세요강', value: 'iframe', slot: true, className: 'el-form-block', required: true }
        ],
        rules: {},
        labelWidth: '130px'
      },
      sortParams: {},
      hasManyJobOption: [],
      hasManyAreaOption: [],
      employeeOption: [],
      noteContent: ''
    }
  },
  mixins: [publicEvents],
  components: {
    myTable,
    FormPage,
    Summernote
  },
  mounted () {
    this.formInfo.data = deepClone(formInfoData)
    this.getJobList()
    this.getEmployee('employee')
    this.getIndustry()
    this.getHasManyJobOption()
    this.getHasManyAreaOption()
    this.initRules()
    this.getCareer('career')
    this.getEndEducation('endEducation')
    this.getSalaryUnit('salaryUnit')
  },
  methods: {
    getEmployee (key) {
      getDictData(key).then(res => {
        this.employeeOption = res.map(item => {
          return {
            label: item.value,
            value: item.idx,
            id: item.id
          }
        })
      })
    },
    getCareer (key) {
      getDictData(key).then(res => {
        this.listTypeInfo.career = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.idx),
            id: item.id
          }
        })
      })
    },
    getEndEducation (key) {
      getDictData(key).then(res => {
        this.listTypeInfo.endEducation = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.idx),
            id: item.id
          }
        })
      })
    },
    getSalaryUnit (key) {
      getDictData(key).then(res => {
        this.listTypeInfo.salaryUnit = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.idx),
            id: item.id
          }
        })
      })
    },
    getHasManyJobOption () {
      getJobIndex().then(res => {
        this.hasManyJobOption = changeOption(res, { value: 'id', label: 'name' })
      })
    },
    getHasManyAreaOption () {
      getAreaIndex().then(res => {
        this.hasManyAreaOption = changeOption(res, { value: 'id', label: 'name' })
      })
    },
    getIndustry () {
      getIndustry().then(res => {
        this.listTypeInfo.industry1 = changeOption(res, { value: 'id', label: 'name' })
      })
    },
    initRules () {
      const formInfo = this.formInfo
      formInfo.rules = this.$initRules(formInfo.fieldList)
    },
    getJobList () {
      const data = {
        ...this.formInline,
        ...this.sortParams,
        page: this.pagination.currentPage,
        per: this.pagination.pageSize
      }
      this.loading = true
      jobApi.getJobList(data).then(res => {
        this.loading = false
        this.data = res.data
        this.pagination.total = res.meta.pagination.total
      }).catch(() => {
        this.loading = false
      })
    },
    sortChange (val) {
      this.pagination.currentPage = 1
      if (val.order === 'ascending') {
        this.sortParams = {
          sort: 'asc',
          order_by: val.prop
        }
      } else if (val.order === 'descending') {
        this.sortParams = {
          sort: 'desc',
          order_by: val.prop
        }
      } else {
        this.sortParams = {}
      }
      this.getJobList()
    },
    handleDeleteJob (id) {
      jobApi.deleteJob({ id }).then(res => {
        this.getJobList()
      })
    },
    confirmAddJob () {
      this.noteContent = ''
      this.dialogForm.title = '추가'
      mergeObjOfValue(this.formInfo.data, formInfoData)
      this.dialogForm.dialogVisible = true
    },
    handleSubmitJob () {
      /* eslint-disable */
      if (this.formInfo.data.id) {
        const params = {
          ...this.formInfo.data
        }
        if (params.industry1 && params.industry1.length) {
          params.industry1 = params.industry1[params.industry1.length - 1]
        }

        for (const prop in params) {
          if (params[prop] instanceof Object) {
            if (params[prop].length) {
              const copyProp = []
              params[prop].forEach((element, index) => {
                const allval = Object.values(element)
                const isEmpty = allval.every(e => e !== '' && e.length !== 0)
                if (isEmpty) {
                  copyProp.push(params[prop][index])
                }
              })
              params[prop] = copyProp
            }
            params[prop] = JSON.stringify(params[prop])
          }
        }

        if (JSON.parse(params.employee).length===3) {
          params['employee1'] = JSON.parse(params.employee)[0].id
          params['employee2'] = JSON.parse(params.employee)[1].id
          params['employee3'] = JSON.parse(params.employee)[2].id
        } else if (JSON.parse(params.employee).length===2) {
          params['employee1'] = JSON.parse(params.employee)[0].id
          params['employee2'] = JSON.parse(params.employee)[1].id
          params['employee3'] = null
        } else if (JSON.parse(params.employee).length===1) {
          params['employee1'] = JSON.parse(params.employee)[0].id
          params['employee2'] = null
          params['employee3'] = null
        } else if (JSON.parse(params.employee).length===0) {
          params['employee1'] = null
          params['employee2'] = null
          params['employee3'] = null
        }
        delete params.employee

        params.iframe = $('#summernote').summernote('code')

        console.log(params)
        jobApi.updateJob(params).then(res => {
          this.getJobList()
          this.dialogForm.dialogVisible = false
          this.$message({
            message: '수정되였습니다.',
            type: 'success'
          })
        })
      } else {
        const params = {
          ...this.formInfo.data
        }
        if (params.industry1 && params.industry1.length) {
          params.industry1 = params.industry1[params.industry1.length - 1]
        }

        for (const prop in params) {
          if (params[prop] instanceof Object) {
            if (params[prop].length) {
              const copyProp = []
              params[prop].forEach((element, index) => {
                const allval = Object.values(element)
                const isEmpty = allval.every(e => e !== '' && e.length !== 0)
                if (isEmpty) {
                  copyProp.push(params[prop][index])
                }
              })
              params[prop] = copyProp
            }
            params[prop] = JSON.stringify(params[prop])
          }
        }

        params.iframe = $('#summernote').summernote('code')
        console.log(params)
        jobApi.updateJob(params).then(res => {
          this.getJobList()
          this.dialogForm.dialogVisible = false
          this.$message({
            message: '수정되였습니다.',
            type: 'success'
          })
        })
      }
    },
    handleEdit (rowData) {
      this.dialogForm.title = '수정'
      const data = {
        ...rowData
      }
      data.employee = []
      if (data.industry1) {
        data.industry1 = getFathersById(data.industry1.id, this.listTypeInfo.industry1, 'value')
      }
      if (data.industry2) {
        data.industry2 = getFathersById(data.industry2.id, this.listTypeInfo.industry1, 'value')
      }
      if (data.industry3) {
        data.industry3 = getFathersById(data.industry3.id, this.listTypeInfo.industry1, 'value')
      }
      if (data.employee1) {
        // data.employee1 = data.employee1.idx
        data.employee.push({id: data.employee1.idx})
      }
      if (data.employee2) {
        // data.employee2 = data.employee2.idx
        data.employee.push({id: data.employee2.idx})
      }
      if (data.employee3) {
        // data.employee3 = data.employee3.idx
        data.employee.push({id: data.employee3.idx})
      }
      console.log(data.employee)
      this.noteContent = rowData.iframe
      this.formInfo.data.id = rowData.id
      mergeObjOfValue(this.formInfo.data, data)
      this.dialogForm.dialogVisible = true
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getJobList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.getJobList()
    },
    emitSelection (val) {
      this.selectionData = val
    },
    currentChange (val) {
      this.pagination.currentPage = val
      this.getJobList()
    }
  }
}
</script>
